package com.nodecollege.cloud.service.impl.deal;

import com.alibaba.fastjson.JSONObject;
import com.nodecollege.cloud.common.exception.NCException;
import com.nodecollege.cloud.common.model.NCResult;
import com.nodecollege.cloud.common.model.po.ChatGroupUser;
import com.nodecollege.cloud.common.model.po.ChatRecord;
import com.nodecollege.cloud.common.model.vo.ChatSignedData;
import com.nodecollege.cloud.common.utils.NCUtils;
import com.nodecollege.cloud.common.utils.ThreadUserUtils;
import com.nodecollege.cloud.service.ChatService;
import com.nodecollege.cloud.service.GroupUserService;
import com.nodecollege.cloud.service.RecordService;
import com.nodecollege.cloud.service.impl.ChatServiceAbstrat;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 好友消息签收
 *
 * @author LC
 * @date 2020/2/26 23:31
 */
@Slf4j
@Service
public class ChatSignedServiceImpl extends ChatServiceAbstrat implements ChatService {

    @Autowired
    private GroupUserService groupUserService;

    @Autowired
    private RecordService recordService;


    @Override
    public void handler(String chatData, Channel channel) {
        log.info("ChatHandlerSignedServiceImpl handler");
        ChatSignedData signedData = JSONObject.parseObject(chatData, ChatSignedData.class);
        if (signedData == null) {
            return;
        }
        Long userId = ThreadUserUtils.getLoginUser().getUserId();
        if (signedData.getGroupId() != null) {
            // 群消息签收
            ChatGroupUser update = new ChatGroupUser();
            update.setGroupId(signedData.getGroupId());
            update.setUserId(userId);
            groupUserService.updateRecordReadTime(update);
            sendMsg(userId, NCResult.ok(update), 5);
            return;
        } else if (NCUtils.isNotNullOrNotEmpty(signedData.getRecordIdList()) && signedData.getSendUserId() != null){
            // 好友消息签收
            for (int i = 0; i < signedData.getRecordIdList().size(); i++) {
                ChatRecord record = new ChatRecord();
                record.setRecordId(signedData.getRecordIdList().get(i));
                record.setReceiveUserId(userId);
                record = recordService.readRecord(record);
                // 给好友发送签收消息
                sendMsg(signedData.getSendUserId(), NCResult.ok(record), 5);
                // 给自己发送签收消息
                sendMsg(userId, NCResult.ok(record), 5);
            }
            return;
        }
        throw new NCException("-1", "参数错误");
    }
}
